Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Arraylist → Java Arraylist

Arraylist

Java Arraylist

ArrayList in Java Collections

The ArrayList class in Java provides a dynamic array-based implementation of the List interface. Characteristics Ordered: Elements are maintained in the order they are added. Resizable: The size of the underlying array can be automatically increased as needed to accommodate new elements. Duplicates allowed: You can add duplicate elements to an ArrayList.

Benefits of ArrayList

Fast random access: Retrieving elements by their index (position) is very efficient (average constant time) due to the array-based structure. Simple to use: The ArrayList class provides a straightforward API for adding, removing, and accessing elements.

Drawbacks of ArrayList

Slower insertions/removals in the middle: Inserting or removing elements in the middle of the list requires shifting elements, which can be slower compared to LinkedList. Potential for wasted space: If you frequently remove elements, the underlying array might not shrink automatically, leading to wasted space.

how to import Arraylist class

Import syntax import java.util.ArrayList;

how to create and initialize an Arraylist

There are two main ways to create and initialize an ArrayList in Java: 1. Creating an empty ArrayList and then adding elements
Creating an empty arraylist example in java import java.util.ArrayList; public class Main { public static void main(String[] args) { // Create an empty ArrayList of strings ArrayList<String> fruits = new ArrayList<>(); // Add elements to the list fruits.add("Apple"); fruits.add("Banana"); fruits.add("Orange"); // Access elements or iterate through the list System.out.println(fruits.get(0)); // Output: Apple (accessing first element) for (String fruit : fruits) { System.out.println(fruit); } } }

Output

Apple Apple Banana Orange
In this example: We use new ArrayList<>() to create an empty ArrayList named fruits. Then, we use the add(E element) method to add elements ("Apple", "Banana", "Orange") to the list. Finally, we can access elements by index (using get(int index)) or iterate through the list using a for-each loop.
2. Creating an ArrayList with initial elements using a collection initializer
Creating an arraylist and adding elements example import java.util.ArrayList; public class Main { public static void main(String[] args) { // Create an ArrayList with initial elements (collection initializer) ArrayList<String> colors = new ArrayList<>() {{ add("Red"); add("Green"); add("Blue"); }}; // Access elements or iterate through the list System.println(colors.size()); for (String color : colors) { System.out.println(color); } } }

Output

3 Red Green Blue
In this example: We use a collection initializer within the ArrayList constructor to directly add elements ("Red", "Green", "Blue") during creation. This approach can be more concise for initializing an ArrayList with some initial values. Both methods achieve the same result: creating an ArrayList with elements. Choose the approach that best suits your needs and coding style. Remember to replace String with the desired data type for your ArrayList.

Common Operations with ArrayList

Adding elementsadd(E element): Adds the element to the end of the list. ⯄ add(int index, E element): Inserts the element at the specified index, shifting elements at or after that index to the right. Accessing elementsget(int index): Returns the element at the specified index. Removing elementsremove(int index): Removes the element at the specified index and returns it. Elements after the removed element are shifted to the left. ⯄ remove(Object o): Removes the first occurrence of the specified element from the list. Iterating through elements You can use a for loop with the index or a for-each loop to iterate through elements. Checking size: size() Returns the number of elements in the list. Basic example of Arraylist
Basic example of arraylist operations import java.util.ArrayList; public class Main { public static void main(String[] args) { // Create an ArrayList of fruits ArrayList<String> fruits = new ArrayList<>(); fruits.add("Apple"); fruits.add("Banana"); fruits.add("Orange"); // Access element by index String firstFruit = fruits.get(0); // "Apple" // Insert element at a specific index fruits.add(1, "Mango"); // Remove element by index fruits.remove(2); // Remove "Orange" // Iterate through elements using for-each loop for (String fruit : fruits) { System.out.println(fruit); } // Check the size of the list int listSize = fruits.size(); System.out.println("Number of fruits: " + listSize); } }

Output

Apple Mango Orange Number of fruits: 3
This example demonstrates basic operations like adding, accessing, removing, iterating, and checking the size of an ArrayList.

Examples of ArrayList containing elements of various datatypes

1. Integers:
Example of Arraylist with integer in java import java.util.*; public class Main{ public static void main(String args[]){ ArrayList<Integer> numbers = new ArrayList<>(); numbers.add(10); numbers.add(20); numbers.add(35); for (int number : numbers) { System.out.println(number); } } }

Output

10 20 35
Explanation : This code creates an ArrayList named numbers that stores integer values. It then iterates through the list and prints each element.
2. Strings:
Example of Arraylist with string in java import java.util.*; public class Main{ public static void main(String args[]){ ArrayList<String> names = new ArrayList<>(); names.add("Alice"); names.add("Bob"); names.add("Charlie"); for (String name : names) { System.out.println(name); } } }

Output

Alice Bob Charlie
Explanation : This code creates an ArrayList named names that stores string values representing names. It iterates through the list and prints each name.
3. Doubles:
Example of using double in Arraylist import java.util.*; public class Main{ public static void main(String args[]){ ArrayList<Double> prices = new ArrayList<>(); prices.add(19.99); prices.add(24.50); prices.add(12.75); for (double price : prices) { System.out.println(price); } } }

Output

19.99 24.5 12.75
Explanation : This code creates an ArrayList named prices that stores double values representing prices. It iterates through the list and prints each price.
4. Characters:
Example of using char in arraylist in java import java.util.*; public class Main{ public static void main(String args[]){ ArrayList<Character> initials = new ArrayList<>(); initials.add('A'); initials.add('B'); initials.add('C'); for (char initial : initials) { System.out.println(initial); } } }

Output

A B C
Explanation : This code creates an ArrayList named initials that stores character values representing initials. It iterates through the list and prints each character.
5. Custom Objects:
Example of using objects in arraylist in java import java.util.*; class Product { int id; String name; double price; public Product(int id, String name, double price) { this.id = id; this.name = name; this.price = price; } } public class Main { public static void main(String[] args) { ArrayList<Product> products = new ArrayList<>(); products.add(new Product(1, "Laptop", 599.99)); products.add(new Product(2, "Headphones", 79.95)); products.add(new Product(3, "Monitor", 199.99)); for (Product product : products) { System.out.println("ID: " + product.id + ", Name: " + product.name + ", Price: $" + product.price); } } }

Output

ID: 1, Name: Laptop, Price: $599.99 ID: 2, Name: Headphones, Price: $79.95 ID: 3, Name: Monitor, Price: $199.99
This code defines a custom class Product with attributes like id, name, and price. It then creates an ArrayList named products that stores instances of the Product class. The code iterates through the list and prints details of each product. Remember, ArrayList can hold elements of any data type as long as you declare the appropriate type parameter within the angle brackets < > when creating the list.

Tutorials